<?php

class AppsController extends Controller
{
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view' , 'delete'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$model = $this->loadModel($id);
		$model->status = $this::$cnAppsStatus[$model->status];
		$this->render('view', array('model' => $model));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Apps;

		if(isset($_POST['Apps']))
		{
			$model->attributes=$_POST['Apps'];
			
			$model->admin_id = Yii::app()->user->id ;
			$model->ctime = date('Y-m-d H:i:s');
			$model->mtime = $model->ctime ;
			if($_POST['Apps']['platform_type'] == '')
				$model->platform_type = 'iphone' ;
			if($_POST['Apps']['app_type']== '')
				$model->app_type = 'app' ;
			if($_POST['Apps']['status']== '')
				$model->status = 'open' ;
			
			if(isset($_GET['category_code']))
				$model->category_code = $_GET['category_code'];
// 			echo '<pre>'.print_r($model->attributes , true) .'</pre>' ; exit ;
			if($model->save() && $this->resetCategoryAppcount($model->category_code))
			{
				$this->redirect(array('view','id'=>$model->app_id));
			}
		}

		$this->setData() ;
		$this->render('create',array(
			'model'=>$model,
			'flag' =>'create' ,
			'categories' => $this::$categories,
			'appsType' => $this::$appsType,
			'appsPlatType' => $this::$appsPlatType,
			'cnAppsStatus' =>$this::$cnAppsStatus,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		$platform_type = $model->platform_type ;
		$app_type = $model->app_type ;
		$category = $model->category_code ;
		$status = $model->status ;
		if(isset($_POST['Apps']))
		{
			$model->attributes=$_POST['Apps'];
			
			$model->admin_id = Yii::app()->user->id ;
			$model->mtime = date('Y-m-d H:i:s');
			$model->last_update = $model->mtime ;
			if($_POST['Apps']['platform_type'] == '')
				$model->platform_type = $platform_type ;
			if($_POST['Apps']['app_type']== '')
				$model->app_type = $app_type;
			if($_POST['Apps']['category_code']== '')
				$model->category_code = $category;
			if($_POST['Apps']['status'] == '')
				$model->status = $status ;
			if($model->save() && $this->resetCategoryAppcount($model->category_code) && $this->resetCategoryAppcount($category , '---'))
			{
				$this->redirect(array('view','id'=>$model->app_id));
			}
		}

		$this->setData() ;
		$this->render('update',array(
			'model'=>$model,
			'flag' =>'update' ,
			'categories' => $this::$categories,
			'appsType' => $this::$appsType,
			'appsPlatType' => $this::$appsPlatType,
			'cnAppsStatus' =>$this::$cnAppsStatus,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$model=new Apps('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Apps']))
			$model->attributes=$_GET['Apps'];

		if(isset($_GET['category_code']))
			$model->category_code = $_GET['category_code'];
		$this->setData() ;
		$this->render('admin',array(
			'model'=>$model,
			'categories' => $this::$categories,
			'appsType' => $this::$appsType,
			'appsPlatType' => $this::$appsPlatType,
			'cnAppsStatus' =>$this::$cnAppsStatus,
			'category_code' =>$model->category_code,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Apps::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='apps-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	/** AppCategories 得到相应的ID以及Name */
	private static $categories = array( ) ;
	/** 数据表tbl_apps的列app_type的所有取值 */
	private static $appsType = array() ;
	/** 数据表tbl_apps的列platform_type的所有取值 */
	private static $appsPlatType = array() ;
	private static $admins_data = array() ;
	
	private static $cnAppsStatus = array('hidden'=>'隐藏',  'open'=>'打开', 'removed'=>'删除');
	
	/**
	 * 从数据库表对应的AppCategories Models中取得相应的属性
	*/
	private function setCategories(){
		$appCategories = AppCategories::model()->findAll() ;
		foreach ($appCategories as $category)
		{
			$this::$categories[$category->category_code] = $category->category_code ;
		}
	}
	
	/**
	 * 从params配置文件中读取appsType
	 */
	private function setAppsType()
	{
		$this::$appsType = Yii::app()->params['tbl_apps']['appsType'] ;
	}
	/**
	 * 从params配置文件中读取appsPlatType
	 */
	private function setAppsPlatType()
	{
		$this::$appsPlatType = Yii::app()->params['tbl_apps']['appsPlatType'] ;
	}
	private function setAdmins()
	{
		$admins = Admin::model()->findAll() ;
		foreach ($admins as $admin) {
			$this::$admins_data[$admin->admin_id] = $admin->nickname;
		}
	}
	/**
	 * 为相应成员变量赋值
	 */
	private function setData()
	{
		$this->setCategories() ;
		$this->setAppsType() ;
		$this->setAppsPlatType() ;
		$this->setAdmins() ;
	}
	
	public function showAdmin($data, $row, $c)
	{
		$this->setAdmins() ;
		return $this::$admins_data[$data->admin_id] ;
	}
	public function showCategory($data, $row, $c)
	{
		$this->setCategories() ;
		return $this::$categories[$data->category_id] ;
	}
	
	public function showSummary($data, $row, $c)
	{
		$summary = $data->summary;
		$summary = strip_tags($summary) ;
		if (strlen ( $summary ) > 20) {
			return substr($summary, 0 , 20 ) .'...........' ;
		}
		return $summary;
	}
	
	public function showStatus($data, $row, $c)
	{
		return $this::$cnAppsStatus[$data->status] ;
	}
	
	private function resetCategoryAppcount($category_code , $flag = 'add')
	{
		$category = AppCategories::model()->findByAttributes(array('category_code'=>$category_code)) ;
		if($flag == 'add')
			$category->apps_count += 1 ;
		else 
			$category->apps_count -= 1 ;
		if($category->update())
			return true ;
		return false ;
// 		echo '<pre>'.print_r($category->attributes , true) .'</pre>' ; exit ;
// 		AppCategories::model()->update() ;
	}
	
}
